package cc.chengheng.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

/**
 * jwt生成和解析 按过期时间
 */
public class 自定义申明 {
    public static void main(String[] args) {
//        JwtIssueAndParseHasExpiration.issueTokenHasExpiration();
        自定义申明.parseTokenHasExpiration();
    }

    /**
     * 签发令牌 自定义申明
     */
    public static String issueTokenHasClaims() {
        long now = System.currentTimeMillis();
        long expiration = now + 60 * 1000;

        String token = Jwts.builder()
                // 设置id{"jti":"888"}
                .setId("888")

                // 签发用户{"sub":"Rose"}
                .setSubject("Rose")

                // 签发时间{"iat":"xxxx"}
                .setIssuedAt(new Date())

                // 加盐
                .signWith(SignatureAlgorithm.HS256, "fengliulin")

                // 自定义申明，参数map
//                .addClaims()
                .claim("login", "xxx.jpg")
                .claim("fengliulin","xxx.png")
                // 生成的token令牌
                .compact();

        System.out.println(token);

        String[] split = token.split("\\.");

        // 头部
        byte[] split1 = Base64.getDecoder().decode(split[0].getBytes(StandardCharsets.UTF_8));
        System.out.println(new String(split1, 0, split1.length));
        // 载荷
        byte[] split2 = Base64.getDecoder().decode(split[1].getBytes(StandardCharsets.UTF_8));
        System.out.println(new String(split2, 0, split2.length));

        // 加密的无法解密
//        byte[] split3 = Base64.getDecoder().decode(split[2].getBytes(StandardCharsets.UTF_8));
//        System.out.println(new String(split3, 0, split3.length));

        return token;
    }

    /**
     * 解析令牌
     */
    public static void parseTokenHasExpiration() {
//        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4ODgiLCJzdWIiOiJSb3NlIiwiaWF0IjoxNjI3MDM1NTUyLCJleHAiOjE2MjcwMzU2MTJ9.2tpViM9kwPeM5ZD_7zYJ4UFnkPDtKXTP3T1VOfR7amY";

        String token = issueTokenHasClaims();

        // Claims存放的是 载荷
        Jws<Claims> fengliulin = Jwts.parser()
                // 签名密钥，也就是加盐
                .setSigningKey("fengliulin")

                .parseClaimsJws(token);

        Claims claims = fengliulin.getBody();

        System.out.println("jti:" + claims.get("jti"));
        System.out.println("sub:" + claims.getSubject());
        System.out.println("iat:" + claims.getIssuedAt());
        System.out.println("fengliulin:" + claims.get("fengliulin"));
        System.out.println("login:" + claims.get("login"));

    }
}
